package servlet;

import domain.Topic;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import services.TopicServicesImpl;
import services.UserServicesImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        UserServicesImpl userServices = new UserServicesImpl();
        TopicServicesImpl topicServices = new TopicServicesImpl();
        HttpSession session = request.getSession();
        try {
            if (method.equals("login")) {//用户登录
                //获取用户发送的数据
                Map<String, String[]> parameterMap = request.getParameterMap();
                //使用BeanUtils封装正在登录的用户
                User loginUser = new User();
                BeanUtils.populate(loginUser, parameterMap);
                //进入服务层判断用户密码是否正确
                User user = userServices.login(loginUser);
                if (user == null) {
                    //登录失败，写入错误信息，跳转回首页
                    request.setAttribute("loginError_msg", "很高兴，你的用户名或密码错误");
                    request.getRequestDispatcher("/indexServlet").forward(request, response);
                } else {
                    //登录成功
                    //获取所有topic
                    List<Topic> allTopic = topicServices.getAllTopic();
                    //将User对象和topic列表分别存入session和request域
                    session.setAttribute("user", user);
                    request.setAttribute("topicList", allTopic);
                    request.getRequestDispatcher("/newspages/admin.jsp").forward(request, response);
                }
            } else if (method.equals("loginOut")){//退出登录
                //在session中移除user对象
                session.removeAttribute("user");
                //存储提示信息
                request.setAttribute("loginError_msg", "您已退出登录");
                //跳转到主页
                request.getRequestDispatcher("/indexServlet").forward(request, response);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

        protected void doGet (HttpServletRequest request, HttpServletResponse response) throws
        ServletException, IOException {
            this.doPost(request, response);
        }
    }
